package cn.chainco.cts.action;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;

import com.opensymphony.xwork2.ActionSupport;

import ch.qos.logback.core.encoder.EncoderBase;
import cn.chainco.cts.iservice.CommonManager;
import cn.chainco.cts.iservice.ICompanyManager;
import cn.chainco.cts.iservice.IFeeManager;
import cn.chainco.cts.iservice.IItemManager;
import cn.chainco.cts.iservice.IUserManager;
import cn.chainco.cts.jdo.Company;
import cn.chainco.cts.jdo.DataDictionary;
import cn.chainco.cts.jdo.DocTemplate;
import cn.chainco.cts.jdo.Employee;
import cn.chainco.cts.jdo.Fee;
import cn.chainco.cts.jdo.Item;
import cn.chainco.cts.jdo.Tag;
import cn.chainco.cts.jdo.User;
import cn.chainco.cts.jdo.WorkFee;
import cn.chainco.cts.jdo.WorkItem;
import cn.chainco.cts.utils.CommUtils;
import cn.chainco.cts.utils.Constants;
import cn.chainco.cts.utils.CookieUtil;
import cn.chainco.cts.utils.VarData;
import cn.chainco.cts.utils.query.Page;

@SuppressWarnings("unchecked")
@InterceptorRef("ctsInterceptors")
public class CompanyAction extends ActionSupport{
	/**
	 * 
	 */
	private static final long serialVersionUID = 7323085687202703456L;
	private User user;
	private Company company;
	private Item item;
	private Fee fee;
	private DataDictionary dataDictionary;
	private Tag tag;
	private CommonManager commonManager;
	private IUserManager userManager;
	private ICompanyManager companyManager;
	private IItemManager itemManager;
	private IFeeManager feeManager;
	
	private String keyword;
	private Page pager;
	private int pageSize=15;
	private int pageNumber=1;

	/**
	 * 到公司页面 
	 * @return
	 */
	@Action("toCompany")
	public String toCompay(){
		@SuppressWarnings("unused")
		HttpServletRequest request = ServletActionContext.getRequest();
		String userId = CookieUtil.getCookieValue(ServletActionContext.getRequest(), "cts_userid");
		String selectCompanyId = CookieUtil.getCookieValue(ServletActionContext.getRequest(), "cts_emplcpyid");
		
		if(CommUtils.isCorrectNumber(userId)){
		   Long l_userId = Long.valueOf(userId);
		   user = this.commonManager.findEntityByPK(User.class, l_userId);
		   if(CommUtils.isCorrectNumber(selectCompanyId)){
			   company = this.commonManager.findEntityByPK(Company.class, Long.valueOf(selectCompanyId));
		   }else if(user!=null){
			   Company c = this.companyManager.findCompayByUser(user);
			   if(c!=null && (c.getStatus() == 0 || c.getStatus() == 2)){
				   company = c;
			   }
		   }
		}
		
	    return "/company/company";	
	}
	
	/**
	 * 保存公司
	 *
	 */
	@Action("saveCompany")
	public void saveCompany(){
		HttpServletRequest request = ServletActionContext.getRequest(); 
		String companyid = request.getParameter("company.id");
		String userId = request.getParameter("company.user.id");
		String isTimeUp = request.getParameter("isTimeUp");
		String timeFileName = request.getParameter("timeFileName");
		
		try{
			if(company!=null){
				if(userId==null || userId==""){
					ActionUtil.outputData("0"); // 失败
				}else{
						String prefixSql = " 1=1 and prefix='"+company.getPrefix()+"'";
						List<Company> companyPrefix = ActionUtil.findListByE(Company.class, prefixSql);
						if(companyPrefix.size() > 0 && companyPrefix.get(0).getId()!=company.getId()){
							ActionUtil.outputData(-1);
							return;
						}
						
						String companyNameSql = " 1=1 and name='" + company.getName() + "'";
						List<Company> companyName = ActionUtil.findListByE(Company.class, companyNameSql);
						if(companyName.size() > 0 && companyName.get(0).getId()!=company.getId()){
							ActionUtil.outputData(-2);
							return;
						}
						
						String companyAdminSql = " 1=1 and userId='" + company.getUser().getId() + "'";
						List<Company> companyAdmin = ActionUtil.findListByE(Company.class, companyAdminSql);
						if(companyAdmin.size() > 0 && companyAdmin.get(0).getId()!=company.getId()){
							ActionUtil.outputData(-3);
							return;
						}
						
						// 更新公司
						if(CommUtils.isCorrectNumber(companyid)){
							
							Company company_0 = this.commonManager.findEntityByPK(Company.class, company.getId());
							company_0.setName(company.getName());
                            company_0.setPrefix(company.getPrefix());
                            company_0.setStatus(company.getStatus());
                            company_0.setUser(company.getUser());
							company_0.setCreateTime(company.getCreateTime());
							company_0.setLogoPath(company.getLogoPath());
							this.commonManager.modifyEntity(company_0);
							ActionUtil.outputData("1"); // 成功
						}else {
								Date createTime = new Date();
								user = this.commonManager.findEntityByPK(User.class, Long.valueOf(userId));
								company.setUser(user);
								company.setCreateTime(createTime);
								Long result = this.commonManager.saveEntity(company);
								if(result > 0){
									try {
										String name = user.getUserName().substring(0 , user.getUserName().indexOf("@"));
										company = this.commonManager.findEntityByPK(Company.class, result);
										Employee employee = new Employee();
										employee.setCompany(company);
										employee.setUser(user);
										employee.setNickname(name);
										employee.setCreateTime(new Date());
										employee.setType(2);
										employee.setInvite(2);
										employee.setStatus(1);
										employee.setAuth1(1);
										employee.setAuth2(1);
										employee.setAuth3(1);
										employee.setAuth4(1);
										employee.setAuth5(1);
										employee.setAuth6(1);
										employee.setAuth7(1);
										employee.setAuth8(1);
										employee.setAuth9(1);
										employee.setAuth10(1);
										Long resultc = this.commonManager.saveEntity(employee);
										
										if(timeFileName!=null && isTimeUp!=null && isTimeUp.equals("true")){
											ActionUtil aUtil = new ActionUtil();
											String from = Constants.BASE_DIR + File.separator + Constants.COMPANY_FILENAME + File.separator + "timeUserFile" + File.separator + timeFileName;
											String to  =  Constants.BASE_DIR + File.separator + Constants.COMPANY_FILENAME + File.separator +  File.separator + result;
							                aUtil.reSetPath(from, to);
										}
										
										if(resultc > 0){
											ActionUtil.outputData("1"); // 成功
										}
									} catch (Exception e) {
										this.commonManager.deleteEntityByPK(Company.class, result);
										e.printStackTrace();
									}
								}
						}
				}
				
			}else{
				ActionUtil.outputData("0");
			}
		}catch(Exception e){
			ActionUtil.outputData("0");
			e.printStackTrace();
		}
		
	}

	@Action("mainMeun")
	public String mainMeun(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String employeeId = CookieUtil.getCookieValue(request, "cts_employeecpyid");
		Employee employee = this.commonManager.findEntityByPK(Employee.class , Long.valueOf(employeeId));
		
		request.setAttribute("employee", employee);
		request.setAttribute("maintype", request.getParameter("maintype"));
		request.setAttribute("searchtype", request.getParameter("searchtype"));
		request.setAttribute("searchstatus", request.getParameter("searchstatus"));
		return "/company/mainMeun";
	}
	
	/**
	 * 公司参数
	 * @return
	 */
	@Action("findCompanyInfo")
	public String findCompanyInfo(){
		HttpServletRequest request = ServletActionContext.getRequest(); 
		String type = request.getParameter("type"); // 1.委托项，1.FCL，2.LCL，3.AIR，4.EXPRESS，5.TRUCKING，6.OTHERS
		String typeDetail = request.getParameter("typeDetail");
		String employeeId = CookieUtil.getCookieValue(request, "cts_employeecpyid");
		Employee employee = this.commonManager.findEntityByPK(Employee.class , Long.valueOf(employeeId));
		
		//
		String searchtype = request.getParameter("searchtype");
		String searchstatus = request.getParameter("searchstatus");
		//
		if(type==null || type.equals("") ){
			if(employee!=null){
				if(employee.getAuth3() == 1){
					type = "item";
				}else if(employee.getAuth6() == 1){ // 文档模版
					type = "file";
				}else if(employee.getAuth10() == 1){
					type = "fee";
				}else if(employee.getAuth4() == 1){
					type = "tag";
				}else if(employee.getAuth5() == 1){ // 访客
					type = "1";
				}
			}else{
				type = "item";
			}
			
			
		}
		
		if(type.equals("item") && (employee==null || employee.getAuth3() !=1)){
			type = "";
		}else if(type.equals("fee") && (employee==null || employee.getAuth10()==null || employee.getAuth10()!=1) ){
			type = "";
		}else if(type.equals("tag") && (employee==null || employee.getAuth4() !=1)){
			type = "";
		}
		
		if(type!=null){
			String companyId = CookieUtil.getCookieValue(ServletActionContext.getRequest(), "cts_emplcpyid");
			company = this.commonManager.findEntityByPK(Company.class, Long.valueOf(companyId));
			String language = CookieUtil.getCookieValue(ServletActionContext.getRequest(), "cts_locale");
			
			if(type.equals("fee")){ // 费用 m
				List<Fee> feeList = this.feeManager.findFeeByCompany(company, keyword, searchstatus, null, null);
				feeList = getPageList(feeList , request);
				request.setAttribute("list", feeList);
				
			}else if(type.equals("tag")){ //标签
				List<Tag> tagList = this.companyManager.findTagByCompany(company , keyword , searchstatus);
				tagList = getPageList(tagList , request);
				request.setAttribute("list", tagList);
			}else if(type.equals("item")){ // 委托项目 m
				List<Item> itemlist = this.itemManager.findItem(company, searchtype, keyword , null ,  searchstatus);
				itemlist = getPageList(itemlist , request);
				request.setAttribute("list", itemlist);
			}
		}
		
		request.setAttribute("employee", employee);
		request.setAttribute("type", type);
		request.setAttribute("typeDetail", typeDetail);
		request.setAttribute("searchstatus", searchstatus);
		request.setAttribute("searchtype", searchtype);
		
		return "/company/mainMeun";
		//return "/company/companyParamList";
	}
	
	
	private <E>List<E> getPageList(List<E> list , HttpServletRequest request){
		pager = new Page();
		pager.setElements(list);
		pager.setPageNumber(pageNumber);
		pager.setPageSize(pageSize);
		pager.setTotalElements(list.size());
	   
		request.setAttribute("pageCount", pager.getLastPageNumber());
	    return pager.getCurrentElements();
	}
	
	/**
	 * 禁用公司参数
	 */
	@Action("stopToUsing")
	public void stopToUsing(){
		HttpServletRequest request = ServletActionContext.getRequest(); 
		String ctstype = request.getParameter("ctstype");
		String id = request.getParameter("id");
		int code = 0;
		try {
			if(ctstype!=null && CommUtils.isCorrectNumber(id)){
				if(ctstype.equals("item")){ // 作业项目 
					Item _item = this.commonManager.findEntityByPK(Item.class, Long.valueOf(id));
					_item.setStatus(1);
					this.commonManager.modifyEntity(_item);
				}else if(ctstype.equals("fee")){ // 费用
					Fee _fee = this.commonManager.findEntityByPK(Fee.class, Long.valueOf(id));
					_fee.setStatus(1);
					this.commonManager.modifyEntity(_fee);
				}else if(ctstype.equals("tag")){ // 标签
					Tag _tag = this.commonManager.findEntityByPK(Tag.class , Long.valueOf(id));
					_tag.setStatus(1);
					this.commonManager.modifyEntity(_tag);
				}else if(ctstype.equals("em0")){ // 员工
				   Employee _employee = this.commonManager.findEntityByPK(Employee.class, Long.valueOf(id));
				   _employee.setStatus(2);
				   this.commonManager.modifyEntity(_employee);
				}
				
				code = 1;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	    ActionUtil.outputData(code);
	}
	
	/**
	 * 费用，委托，字典(单个信息)
	 * @return
	 */
	@Action("findCompanySingleInfo")
	public String findCompanySingleInfo(){
		HttpServletRequest request = ServletActionContext.getRequest(); 
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=utf-8");
		
		String type = request.getParameter("type");
		String typeDetail = request.getParameter("typeDetail");
		String id = request.getParameter("id");
		String companyId = CookieUtil.getCookieValue(ServletActionContext.getRequest(), "cts_emplcpyid");
		String language =CookieUtil.getCookieValue(ServletActionContext.getRequest(), "cts_locale");
		
		if(type !=null){
			if(type.equals("item")){
				if(CommUtils.isCorrectNumber(id)){
					item = this.commonManager.findEntityByPK(Item.class, Long.valueOf(id));
				}
				
				Company company = this.commonManager.findEntityByPK(Company.class, Long.valueOf(companyId));
				List<Fee> feeList = this.feeManager.findFeeByCompany(company , 0);
				
				List<Fee> leftFeelist = new ArrayList<Fee>();
				List<Fee> rightFeelist = new ArrayList<Fee>();
			    
				if(item!=null && item.getFees()!=null && item.getFees()!=""){
					for (int i=0 ; i<feeList.size();i++) {
				      Fee fee  = feeList.get(i);
					  // 记录选中的费用
						  Pattern p = Pattern.compile(","+fee.getId()+",");
						  Matcher m = p.matcher(item.getFees());
						  if(m.find()){
							  rightFeelist.add(fee);
						  }else{
							  leftFeelist.add(fee);
						  }
					  }
			    }else{
			    	leftFeelist = feeList;
			    }
				
			    feeList = reValToName(feeList);
			    rightFeelist = reValToName(rightFeelist);
				request.setAttribute("leftFeelist", leftFeelist);
				request.setAttribute("rightfeelist", rightFeelist);
			}else if(type.equals("tag") &&  CommUtils.isCorrectNumber(id)){
				tag = this.commonManager.findEntityByPK(Tag.class, Long.valueOf(id));
			}else if(type.equals("fee") &&  CommUtils.isCorrectNumber(id)){
				fee = this.commonManager.findEntityByPK(Fee.class, Long.valueOf(id));
				if(fee.getItem()!=null){
					Item fee_item = this.commonManager.findEntityByPK(Item.class,  fee.getItem().getId());
					fee.setItem(fee_item);
				}
			}else if(CommUtils.isCorrectNumber(id)){
				//dataDictionary = this.commonManager.findEntityByPK(DataDictionary.class, Long.valueOf(id));
			}
			
		}
		
		request.setAttribute("type", type);
		request.setAttribute("typeDetail", typeDetail);
		request.setAttribute("id", id);
		
		return "/company/addData";
	}
	
	@SuppressWarnings("unused")
	private List<Fee> reValToName(List<Fee> feelist){
		List<Fee> __feelist = feelist;
		String language =CookieUtil.getCookieValue(ServletActionContext.getRequest(), "cts_locale");
		return __feelist;
	}
	
	/**
	 * 费用，委托，字典(单个信息)保存
	 * @return
	 */
	@Action("saveCompanySingleInfo")
	public void saveCompanySingleInfo(){
		HttpServletRequest request = ServletActionContext.getRequest(); 
		String type = request.getParameter("type");
		String id = request.getParameter("id");
		String itemId = request.getParameter("itemId");
		
		String companyId = CookieUtil.getCookieValue(ServletActionContext.getRequest(), "cts_emplcpyid");
		
		try {
			if(type !=null){
				if(type.equals("fee") && fee!=null){ // 费用
				   Company _company = this.commonManager.findEntityByPK(Company.class, Long.valueOf(companyId));
				   if(itemId!=null && !itemId.equals("")){
					   Item item = this.commonManager.findEntityByPK(Item.class, Long.valueOf(itemId));
					   fee.setItem(item);
				   }
				   
				   fee.setCompany(_company);
				   if(CommUtils.isCorrectNumber(id)){
					   fee.setId(Long.valueOf(id));
					   this.commonManager.modifyEntity(fee);
				   }else{
					   Long result = this.commonManager.saveEntity(fee);
					   id = result.toString();
				   }
				   
				   ActionUtil.outputData("1");
				}else if(type.equals("tag")){ // 标签
					 Company _company = this.commonManager.findEntityByPK(Company.class, Long.valueOf(companyId));
					 tag.setCompany(_company);
					 if(CommUtils.isCorrectNumber(id)){
						  tag.setId(Long.valueOf(id));
						  this.commonManager.modifyEntity(tag);
					  }else{
					       Long result = this.commonManager.saveEntity(tag);
					       id = result.toString();
					  }
						 
					  ActionUtil.outputData("1");
				}else if(type.equals("item") && item!=null){ // 委托
					 Company _company = this.commonManager.findEntityByPK(Company.class, Long.valueOf(companyId));
					 item.setCompany(_company);
					 if(CommUtils.isCorrectNumber(id)){
					   item.setId(Long.valueOf(id));
					   this.commonManager.modifyEntity(item);
					 }else{
						 Long result = this.commonManager.saveEntity(item);
						 id = result.toString();
					 }
					 
					 ActionUtil.outputData("1");
				}else{ // 数据字典
					
				}
			}
		} catch (NumberFormatException e) {
			ActionUtil.outputData("0");
			e.printStackTrace();
		}
	}
	
	/**
	 * 验证委托项目的相关费用
	 *
	 */
	@Action("vailAboutFeeForItem")
	public void vailAboutFeeForItem(){
		HttpServletRequest request = ServletActionContext.getRequest(); 
		List<String> feeStrlist = new ArrayList<String>();
		List<Fee> feelist = new ArrayList<Fee>();
		String id = request.getParameter("id");
		String selFeeAry = request.getParameter("selectId");
		
        String resulutStr = "";
        if(CommUtils.isCorrectNumber(id)){
        	Item item = this.commonManager.findEntityByPK(Item.class, Long.valueOf(id));
        	String feeStr = item.getFees();
        	Pattern p = Pattern.compile("^,|,$");
        	Matcher m = p.matcher(feeStr);
        	feeStr = m.replaceAll("");
        	
        	if(feeStr.length() > 0){
        		String[] feeAry = feeStr.split(",");
        		for(int i=0;i<feeAry.length;i++){
        			String feeIdStr = feeAry[i];
        			String sql = " 1=1 and feeId="+feeIdStr;
        			List<WorkFee> wflist = ActionUtil.findListByE(WorkFee.class, sql);
        			if(wflist.size() > 0){
        				feeStrlist.add(feeIdStr);
        			}
        		}
        		
        		if(feeStrlist.size() > 0){
        			for (String idStr : feeStrlist) {
						Pattern pp2 = Pattern.compile(","+idStr+",");
						Matcher mm2 = pp2.matcher(selFeeAry);
						if(!mm2.find()){
						   Fee fee = this.commonManager.findEntityByPK(Fee.class, Long.valueOf(idStr));
						   feelist.add(fee);
						}
						
					}
        		}
        	}
        }
        
        if(feelist.size() > 0){
        	ActionUtil.outputData(resulutStr);
        }else{
        	ActionUtil.outputData("0");
        }
	}
	
	/**
	 * 模糊查找作业项目
	 *
	 */
	@Action("findItemToJson")
	public void findItemToJson(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String name = request.getParameter("itemName");
		String companyId = CookieUtil.getCookieValue(request, "cts_emplcpyid");
		
		if(name !=null && name!=""){
			String sql = " 1=1 and status=0 and  name_zh like '%"+name+"%' and companyId="+companyId;
			List<Item> itemList = ActionUtil.findListByE(Item.class, sql);
			String jStr="";
			
			if(itemList.size() > 0){
				for (Item item : itemList) {
					if(1==1){
						jStr += "{'id':'"+item.getId()+"','name':'"+item.getName()+"'},";
					}
				}
				
				if(jStr.trim().length() > 0){
					jStr = jStr.substring(0 , jStr.length()-1);
				}
			}
			
			String jsonStr = "["+jStr+"]";
			ActionUtil.outputData(jsonStr);
		}
	}
	
	/**
	 * 删除【费用，委托，字典(单个信息)】
	 *
	 */
	@Action("delCompanySingleInfo")
	public void delCompanySingleInfo(){
		HttpServletRequest request = ServletActionContext.getRequest(); 
		String type = request.getParameter("type");
		String id = request.getParameter("id");
		
		try {
			if(type!=null && CommUtils.isCorrectNumber(id)){
				if(type.equals("fee")){ // 费用
					String sql = " select * from cts_workfee where 1=1 and feeId=%s ";
					sql = String.format(sql, id);
					List<WorkFee> workFeeist = this.userManager.findSqlByElist(sql, WorkFee.class, null);
					
				    sql = " select * from cts_item where 1=1 and fees like '%,"+id+",%'";
					List<Item> itemist = this.userManager.findSqlByElist(sql, Item.class, null);
					
					if(workFeeist.size() > 0 || itemist.size() > 0){
						ActionUtil.outputData("2"); // 费用已使用
					}else{
						this.commonManager.deleteEntityByPK(Fee.class, Long.valueOf(id));
						ActionUtil.outputData("1");
					}
				}else if(type.equals("item")){ // 委托
					String sql = " select * from cts_workitem where 1=1 and itemId=%s ";
					sql = String.format(sql, id);
					List<WorkItem> workItemList = this.userManager.findSqlByElist(sql, WorkItem.class, null);
					if(workItemList.size() > 0){
						ActionUtil.outputData("2"); // 委托已使用
					}else{
						this.commonManager.deleteEntityByPK(Item.class, Long.valueOf(id));
						ActionUtil.outputData("1");
					}
				}else if(type.equals("tag")){ // 标签
					this.commonManager.deleteEntityByPK(Tag.class, Long.valueOf(id));
					ActionUtil.outputData("1");
				}else{ // 字典
					
				}
			}else{
				ActionUtil.outputData("0");
			}
		} catch (NumberFormatException e) {
			ActionUtil.outputData("0");
			e.printStackTrace();
		}
		
	}

	public CommonManager getCommonManager() {
		return commonManager;
	}

	public void setCommonManager(CommonManager commonManager) {
		this.commonManager = commonManager;
	}

	public Company getCompany() {
		return company;
	}

	public void setCompany(Company company) {
		this.company = company;
	}

	public ICompanyManager getCompanyManager() {
		return companyManager;
	}

	public void setCompanyManager(ICompanyManager companyManager) {
		this.companyManager = companyManager;
	}

	public DataDictionary getDataDictionary() {
		return dataDictionary;
	}

	public void setDataDictionary(DataDictionary dataDictionary) {
		this.dataDictionary = dataDictionary;
	}

	public Fee getFee() {
		return fee;
	}

	public void setFee(Fee fee) {
		this.fee = fee;
	}

	public IFeeManager getFeeManager() {
		return feeManager;
	}

	public void setFeeManager(IFeeManager feeManager) {
		this.feeManager = feeManager;
	}

	public Item getItem() {
		return item;
	}

	public void setItem(Item item) {
		this.item = item;
	}

	public IItemManager getItemManager() {
		return itemManager;
	}

	public void setItemManager(IItemManager itemManager) {
		this.itemManager = itemManager;
	}

	public Tag getTag() {
		return tag;
	}

	public void setTag(Tag tag) {
		this.tag = tag;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public IUserManager getUserManager() {
		return userManager;
	}

	public void setUserManager(IUserManager userManager) {
		this.userManager = userManager;
	}
	public String getKeyword() {
		return keyword;
	}
	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}
	public int getPageNumber() {
		return pageNumber;
	}
	public void setPageNumber(int pageNumber) {
		this.pageNumber = pageNumber;
	}
	public Page getPager() {
		return pager;
	}
	public void setPager(Page pager) {
		this.pager = pager;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	

}
